package com.shxc.smarttrade.old.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.old.adapternew.MessageAdapter;
import com.shxc.smarttrade.old.bean.EventDatas;
import com.shxc.smarttrade.old.bean.MessageBean;
import com.shxc.smarttrade.old.constants.EventContents;
import com.shxc.smarttrade.old.constants.URLContents;
import com.shxc.smarttrade.old.myinterface.RecyclerViewItemClickListener;
import com.shxc.smarttrade.old.myview.MyFootView;
import com.shxc.smarttrade.old.myview.MyRefreshHeadView;
import com.shxc.smarttrade.old.myview.RecycleViewDivider;
import com.shxc.smarttrade.old.utils.BaseUtils;
import com.shxc.smarttrade.old.utils.Logger;
import com.shxc.smarttrade.old.utils.MyOkHttpUtils;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by jcdev1 on 2017/10/30.
 */

public class MessageActivity extends BaseActivity {
    @BindView(R.id.tv_center)
    TextView tvCenter;
    @BindView(R.id.x_recycler_view)
    XRecyclerView xRecyclerView;
    @BindView(R.id.tv_right)
    TextView tvRight;

    private boolean isRefresh = false;
    private int page = 1;
    private List<MessageBean.DataBean> allList = new ArrayList<>();
    private MessageAdapter adapter;


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    if (xRecyclerView != null)
                        xRecyclerView.refreshComplete();
                    if (isRefresh) {
                        allList.clear();
                        adapter.notifyDataSetChanged();
                    }

                    List<MessageBean.DataBean> db = (List<MessageBean.DataBean>) msg.obj;
                    if (db != null && db.size() > 0) {
                        allList.addAll(db);
                        adapter.setDatas(allList);
                    } else {
                        if (xRecyclerView != null)
                            xRecyclerView.setNoMore(true);
                        if (allList.size() != 0)
                            BaseUtils.showToast("已加载全部！", MessageActivity.this);
                    }
                    isRefresh = false;
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycler);
        ButterKnife.bind(this);
        initView();
        initListener();
        initData();
    }

    private void initView() {
        tvCenter.setText("消息中心");
        tvRight.setText("一键已读");

        LinearLayoutManager manager = new LinearLayoutManager(this);
        xRecyclerView.setLayoutManager(manager);
        xRecyclerView.addItemDecoration(new RecycleViewDivider(this, LinearLayout.VERTICAL, 20, getResources().getColor(R.color.all_background)));
        xRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        xRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);
        MyRefreshHeadView myRefreshHeadView = new MyRefreshHeadView(this);
        myRefreshHeadView.setArrowImageView(R.mipmap.indicator_arrow);
        xRecyclerView.setRefreshHeader(myRefreshHeadView);
        xRecyclerView.setFootView(new MyFootView(this));
        xRecyclerView.setAdapter(adapter = new MessageAdapter(this));
    }


    private void initListener() {
        xRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        isRefresh = true;
                        page = 1;
                        initData();
                    }
                }, 1000);

            }

            @Override
            public void onLoadMore() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        page++;
                        initData();
                    }
                }, 1000);

            }
        });
        adapter.setMyItemCLickListener(new RecyclerViewItemClickListener() {
            @Override
            public void onItemCLick(int position, Object object) {
                Intent intent = new Intent(MessageActivity.this, MessageDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("message", (MessageBean.DataBean) object);
                intent.putExtras(bundle);
                startActivityForResult(intent, 110);
            }
        });
    }

    @OnClick({R.id.rl_left, R.id.tv_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_left:
                finish();
                break;
            case R.id.tv_right:
                isRefresh = true;
                quickRead();
                break;
        }
    }

    private void initData() {
        getMessage();
    }

    private void getMessage() {
        showShortDialog();
        Map<String, Object> map = new HashMap<>();

        map.put("accessToken", accessTokenss);
        map.put("userId", userIdss);
        map.put("page", String.valueOf(page));
        map.put("pageSize", String.valueOf(10));
        MyOkHttpUtils.getServiceDatas(this,map, URLContents.MESSAGE_ACTIVITY_MSG_LIST, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                dismissShortDialog();
                BaseUtils.showToast("网络异常", MessageActivity.this);
            }

            @Override
            public void success(String response, int id) {
                dismissShortDialog();
                if (response != null) {
                    Gson gson = new Gson();
                    MessageBean ib = gson.fromJson(response, MessageBean.class);
                    if (ib.getErr_code().equals("0")) {
                        Message msg = Message.obtain();
                        msg.what = 0;
                        msg.obj = ib.getData();
                        handler.sendMessage(msg);
                    } else {
                        BaseUtils.showToast(ib.getErr_msg(), MessageActivity.this);
                    }

                }

            }
        });
    }

//    @Override
//    protected void onResume() {
//        super.onResume();
//        initData();
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().post(new EventDatas(EventContents.MESSAGE_ACTIVITY_READ_MSG, null));
    }

    private void quickRead() {
        showShortDialog();
        Map<String, Object> map = new HashMap<>();

        map.put("accessToken", accessTokenss);
        map.put("userId", userIdss);
        MyOkHttpUtils.getServiceDatas(this,map, URLContents.MESSAGE_ACTIVITY_QUICK_READ, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                showToast("网络异常");
                dismissShortDialog();
            }

            @Override
            public void success(String response, int id) {
                JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                String errCode = "";
                String errMsg = "";
                if (!jsonObject.get("err_code").isJsonNull())
                    errCode = jsonObject.get("err_code").getAsString();
                if (!jsonObject.get("err_msg").isJsonNull())
                    errMsg = jsonObject.get("err_msg").getAsString();
                if (errCode.equals("0"))
                    getMessage();
                else
                    showToast(errMsg);

                dismissShortDialog();
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Logger.e("requestCode:", requestCode + "  resultCode: " + resultCode);
        if (requestCode == 110 && resultCode == 111) {
            page = 1;
            isRefresh = true;
            initData();
        }
    }
}
